import tkinter as tk
from tkinter import scrolledtext
from tkinter import filedialog
import tdxserver
from contextlib import redirect_stdout
import io
import threading
import time
from tkinter import messagebox
import subprocess
import configparser
import os



class GUI:
    def __init__(self, root):
        self.root = root
        root.title("TDX DLL Server")
        root.resizable(False, False)
        self.output_window = scrolledtext.ScrolledText(root, width=50, height=20)
        self.output_window.pack()
        
        self.start_button = tk.Button(root, text="启动服务", command=self.start_server)
        self.start_button.pack(side=tk.LEFT, padx=10)
        
        self.refresh_button = tk.Button(root, text="刷新模块", command=self.refresh_module)
        self.refresh_button.pack(side=tk.LEFT, padx=10)

        self.stop_button = tk.Button(root, text="关闭服务", command=self.stop_module)
        self.stop_button.pack(side=tk.LEFT, padx=10)

        self.tdx_button = tk.Button(root, text="启动通达信", command=self.tdx_module)
        self.tdx_button.pack(side=tk.LEFT, padx=10)
        
        self.server_running = False
        self.update_buttons()


    def start_server(self):
        import importlib
        importlib.reload(tdxserver)    
        self.output_window.delete(1.0, tk.END)       
        self.tlog("启动服务")
        thread = threading.Thread(target=tdxserver.pipe_server, args=(self.on_server_exit,self.tlog))
        thread.start()
        self.server_running = True
        self.update_buttons()
        
    def refresh_module(self):
        self.tlog("刷新tdx模块")
        tdxserver.reload_tdx_module()

    def stop_module(self):
        if tdxserver.isConnect>0:
            self.tlog("关闭服务")
            tdxserver.closeserever()
        else:
            self.tlog("服务已经关闭")

    def tdx_module(self):
        #self.withdraw()  # 隐藏主窗口
        # 弹出文件选择对话框
        file_path = filedialog.askopenfilename(title="选择文件")
        # 检查是否选择了文件
        if file_path:
            # 创建配置解析器
            config = configparser.ConfigParser()
            # 配置文件名
            config_file = 'config.ini'
            # 检查配置文件是否存在，若不存在，则创建
            if not os.path.exists(config_file):
                config['Paths'] = {}  # 创建 'Paths' 部分
            else:
                config.read(config_file)
            # 更新或添加 'tdxpath' 路径
            config['Paths']['tdxpath'] = file_path
            # 将更新后的配置写回文件
            with open(config_file, 'w') as configfile:
                config.write(configfile)
                dpath = os.path.dirname(file_path)
                subprocess.Popen([file_path], cwd=dpath)
                self.tdx_button.config(state=tk.DISABLED)
                



    def update_buttons(self):
        if self.server_running:
            self.start_button.config(state=tk.DISABLED)
            self.refresh_button.config(state=tk.NORMAL)
            self.stop_button.config(state=tk.NORMAL)
        else:
            self.start_button.config(state=tk.NORMAL)
            self.refresh_button.config(state=tk.DISABLED)
            self.stop_button.config(state=tk.DISABLED)

    def closewindow(self):
        time.sleep(0.3)
        self.root.destroy()

    def on_server_exit(self):
        self.tlog("服务程序退出!")
        self.server_running = False
        self.update_buttons()
        #threading.Thread(target= self.closewindow).start()

    

    def tlog(self,msg):
        with io.StringIO() as buf, redirect_stdout(buf):
            print(msg)
            output = buf.getvalue()
            self.output_window.insert(tk.END, output)




root = tk.Tk()

def on_closing():
    if tdxserver.isConnect==0:
        root.destroy()
    else:
        messagebox.showinfo("提醒", "请关闭服务后再退出！")
        return False
            
        

root.protocol("WM_DELETE_WINDOW", on_closing)

gui = GUI(root)
gui.start_server()


# 创建一个配置解析器
config = configparser.ConfigParser()
# 配置文件路径
config_file = 'config.ini'
# 检查文件是否存在
if os.path.exists(config_file):
    # 读取配置文件
    config.read(config_file)
    # 检查 'Paths' 部分是否存在
    if 'Paths' in config:
        try:
            # 获取 'tdxpath' 的值
            exepath = config.get('Paths', 'tdxpath')
            dpath = os.path.dirname(exepath)
            subprocess.Popen([exepath], cwd=dpath)
            gui.tdx_button.config(state=tk.DISABLED)
        except configparser.NoOptionError:
            print("'tdxpath' 选项在 'Paths' 部分中不存在.")


root.mainloop()
